#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <openssl/md5.h>

//gcc rsa.c -lssl -l crypto

int main(int argc,char *argv[])
{
    int ret = -1;
    MD5_CTX c;
    FILE *fp;
    size_t len;
    uint8_t *rd_buf;
    struct stat buf;
    unsigned char md[16];

    fp = fopen("CA.pem","r");
    if(!fp)
    {
        perror("fopen");
        return ret;
    }
    fstat(fileno(fp),&buf);
    rd_buf = (uint8_t *)calloc(1,buf.st_size);
    len = fread(rd_buf,1,buf.st_size,fp);
    if(len != buf.st_size)
    {
        if(ferror(fp))
        {
            clearerr(fp);
            printf("fread error..\r\n");
        }
    }

/*********************************方式一******************************/
    ret = MD5_Init(&c);
    if(ret != 1)
    {
        printf("MD5_init error..\r\n");
    }
    for(size_t i = 0;i < len;i++)
    {
        ret = MD5_Update(&c,(const uint8_t *)&rd_buf[i],1);
        if(ret != 1)
        {
            printf("MD5_Update error..\r\n");
        }
    }
    ret = MD5_Final(md,&c);
    if(ret != 1)
    {
        printf("MD5_Final error..\r\n");
    }
    printf("md5sum:");
    for(size_t i = 0;i < sizeof(md);i++)
    {
        printf("%02x",md[i]);
    }
    printf("\r\n");

/*********************************方式二******************************/
    memset(md,0,sizeof(md));
    MD5((const uint8_t *)rd_buf,buf.st_size,md);
    printf("md5sum:");
    for(size_t i = 0;i < sizeof(md);i++)
    {
        printf("%02x",md[i]);
    }
    printf("\r\n");

    fclose(fp);
    free(rd_buf);

    return 0;
}